import tkinter as tk
from tkinter import filedialog
import tkinter.messagebox
from docx import Document
import os

window = tk.Tk()
window.title('Kindle Clippings转换工具')
# window.geometry('500x300')

in_file = tk.StringVar
out_file = tk.StringVar

def select_input():
    global in_file
    in_file = filedialog.askopenfilename(title = '选择“My Clippings.txt”', filetypes = (("文本文件","*.txt"), ("all files","*.*")))
    global in_entry
    in_entry.insert(0, in_file)

def select_output():
    # out_clippings = filedialog.asksaveasfilename(title = '选择输出文件', filetypes = (("Office Word","*.docx"), ("Markdown", "*.md"), ("all files","*.*")))
    # out_clippings.set(out_clippings_)
    #获取输出文件夹
    global out_file
    out_file = filedialog.askdirectory()
    global out_entry
    out_entry.insert(0, out_file)


# 选择输入和输出文件
# 输入
tk.Label(window, text='Kindle标注：').grid(row = 0, column = 0)
in_entry = tk.Entry(window)
in_entry.grid(row = 0, column = 1)
tk.Button(window, text = '选择', command = select_input).grid(row = 0, column = 2)

# 输出
tk.Label(window, text='输出文件夹：').grid(row = 1, column = 0)
out_entry = tk.Entry(window)
out_entry.grid(row = 1, column = 1)
tk.Button(window, text = '选择', command = select_output).grid(row = 1, column = 2)

# 输出文件类型
# out_format = [('Markdown (md)', 0), ('Word (docx)'), 1]

# 输出文件标题
out_title = tk.StringVar()
tk.Label(window, text='输出文件标题：').grid(row = 2, column = 0)
title_entry = tk.Entry(window)
title_entry.grid(row = 2, column = 1)
title_entry.insert(0, 'My Clippings')

# 是否输出时间和位置
position_time = tk.BooleanVar()
# export_position_time = False
tk.Checkbutton(window, text='输出时间和位置', variable=position_time, onvalue=True, offvalue=False, command='').grid(row = 3, column = 1)

# command
def convert_clip():
    global in_file, out_file, title_entry, position_time
    in_clippings = str(in_file)
    in_clippings_name = os.path.basename(in_clippings)
    #直接输出docx
    out_clippings = os.path.join(str(out_file), in_clippings_name+'.docx')

    out_clippings_format = out_clippings.split('.')[-1]

    # Kindle的My Clippings.txt中每条文摘以“==========”分割
    clippings = open(in_clippings, 'r').read().split('==========\n')

    title = title_entry.get()
    export_position_time = position_time.get()

    # 以字典存文摘，书名为索引
    clip_out = {}

    # 最后一个clipping为空
    for i in clippings[:-1]:
        clip = i.strip().split('\n')
        book = clip[0].strip()
        position_time = clip[1].strip().split('|')
        position = position_time[0].strip()
        time = position_time[1].strip()
        time_position = time+' '+position
        note = '\n'.join(clip[2:]).strip()

        # 以书名为索引存入字典
        try:
            clip_out[book][time_position] = note
        # 若书名不存在，新建书名字典
        except:
            clip_out[book] = dict()
            clip_out[book][time_position] = note

    # 根据后缀输出不同格式
    if out_clippings_format == 'docx':
        # 输出docx格式
        document = Document('zh-template.docx')
        document.add_heading(title, level = 0)
        for k in clip_out.keys():
            document.add_heading(k, level = 1)
            for kk in clip_out[k].keys():
                if export_position_time:
                    document.add_paragraph(kk)
                    document.add_paragraph(clip_out[k][kk])
                else:
                    document.add_paragraph(clip_out[k][kk])
        document.save(out_clippings)
    else:
        # 若非docx，输出markdown格式
        with open('%s.md' %out_clippings, 'w') as out_md:
            out_md.write('---\ntitle: %s\n---\n\n' %title)
            for k in clip_out.keys():
                out_md.write('# %s\n\n' %k)
                for kk in clip_out[k].keys():
                    if export_position_time:
                        out_md.write('%s\n\n>%s\n\n' %(kk, clip_out[k][kk]))
                    else:
                        out_md.write('>%s\n\n' %(clip_out[k][kk]))
    # message
    tkinter.messagebox.showinfo('转换完毕', title + '转换完毕。')

tk.Button(window, text='开始转换', width=15, height=2, command=convert_clip).grid(row = 4, column = 1)

window.mainloop()
